﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.IO;
using System.Drawing;
using Microsoft.Win32;

namespace FileExplorer
{
    /// <summary>
    /// 获取指定文件的Icon图像getIcon()、getIcon2()
    /// </summary>
    class FileIcon
    {
        private const uint SHGFI_ICON = 0x100;
        private const uint SHGFI_LARGEICON = 0x0;  //大图标
        private const uint SHGFI_SMALLICON = 0x1;  //小图标

        [StructLayout(LayoutKind.Sequential)]
        public struct SHFILEINFO
        {
            public IntPtr hIcon;        //文件的图标句柄  

            public IntPtr iIcon;        //图标的系统索引号  

            public uint dwAttributes;   //文件的属性值  

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;//文件的显示名  


            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;   //文件的类型名  
        };

        [DllImport("shell32.dll")]
        private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);

        /// <summary>
        /// 获取文件FilePath对应的Icon
        /// </summary>
        public static Icon getIcon(string FilePath)
        {
            SHFILEINFO shinfo = new SHFILEINFO();
            //FileInfo info = new FileInfo(FileName);

            //大图标
            SHGetFileInfo(FilePath, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_LARGEICON);
            Icon largeIcon = Icon.FromHandle(shinfo.hIcon);

            //Icon.ExtractAssociatedIcon(FileName);
            return largeIcon;
        }

        /// <summary>
        /// 获取文件FilePath对应的Icon
        /// </summary>
        public static Icon getIcon2(string FilePath)
        {
            return Icon.ExtractAssociatedIcon(FilePath);
        }
    }
}
